package com.kznnc.data_structure.structure.linkedStructure;

/**
 * 循环链表
 * <p>
 * 怎么初始化一个循环队列？
 */
public class CycleLinkedStructure {
    /**
     * 头节点
     */
    private Node head;
    /**
     * 尾节点
     */
    private Node tail;
    /**
     * 实际容量大小
     */
    private int size;


    public void insert(Integer data) {
        Node node = new Node(data);
        if (head == null) {
            head = node;
            tail = node;
            size++;
            return;
        }
        tail.next = node;
        node.next = head;
        tail = node;
        size++;
    }

    public Integer getIndexData(Integer index) {
        if (size <=0){
            throw  new RuntimeException("遍历空指针");
        }
        if (index == size - 1) {
            return tail.data;
        }
        Node node = head;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node.data;
    }

    public void remove(Integer data) {
        Node node = head;
        if (size <=0){
            throw new RuntimeException("越界了");
        }
        if (size ==1){
            if (head.data.equals(data)){
                head = null;
                tail = null;
                size --;
                return;
            }
        }
        for (int i = 0; i < size; i++) {
            if (node == null) {
                throw new RuntimeException("空指针");
            }
            if (node.next.data.equals(data)) {
                break;
            }
            node = node.next;
        }
        if (node.next == head) {
            head = node.next.next;
        }
        if (node.next == tail) {
            tail = node.next.next;
        }
        node.next = node.next.next;
        size--;
    }


    public static void main(String[] args) {
        CycleLinkedStructure cycleLinkedStructure = new CycleLinkedStructure();
        for (int i = 0; i < 2; i++) {
            cycleLinkedStructure.insert(i);
        }
        cycleLinkedStructure.remove(1);
        for (int i = 0; i < 1; i++) {
            System.out.println(cycleLinkedStructure.getIndexData(i));
        }
    }

    class Node {
        private Integer data;
        private Node next;
        private Node pre;

        public Node(Integer data) {
            this.data = data;
            this.next = null;
            this.pre = null;
        }

        public Node getPre() {
            return pre;
        }

        public void setPre(Node pre) {
            this.pre = pre;
        }

        public Integer getData() {
            return data;
        }

        public void setData(Integer data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }


}
